How to check if file exists or not in bash?

Member

by marina , in category: Other , 2 years ago

How to check if file exists or not in bash?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@marina You can use [ -f "path_to_file" ]; to check if file exist or not in Bash, here is code as example:


1
2
3
4
5
6
PATH="/tmp/test.txt"
if [ -f "$PATH" ]; then
  echo "File exist!"
else
  echo "File does not exists!"
fi


Member

by vivien , a year ago

@marina 

You can use the test or [ command to check if a file exists and determine what type of file it is in bash. For example, you can use the following command to check if a file named "file.txt" exists in the current directory:

1
2
3
4
5
if [ -e "file.txt" ]; then
  echo "file exists"
else
  echo "file does not exist"
fi


You can also use the -f option to check if the file is a regular file:

1
2
3
4
5
if [ -f "file.txt" ]; then
  echo "file is a regular file"
else
  echo "file is not a regular file"
fi